<?php

class ServiceController extends Core_Controller_Action {

    public function indexAction() {
        
    }

    public function detailAction() {
        $id = $this->_getParam("gid");

        if(is_null($id) || empty($id)){
            $this->_handlePageNotFound();
        }

        $info_db = new Core_Model_DbTable_GeneralInformation();
        $info = $info_db->getFullJoin($id);
        if(!$info){
            $this->_handlePageNotFound();
        }
        $this->view->generalinfo = $info;
        
        $step = $this->_getParam("step");
        switch($step) {
            case "dunnage":
                $this->detailDunnage();
                break;
            case "tally":
                break;
            case "cargo":
                $this->detailCargo();
                break; 
        }
    }

    public function detailDunnage() {
        $id = $this->_getParam("id");
        if(is_null($id) || empty($id)){
            $this->_handlePageNotFound();
        }

        $dunnage_operation_db = new Core_Model_DbTable_DunnageOperations();
        $dunnage_operation_info = $dunnage_operation_db->getDunnageOperation($id);

        $dunnage_material_db = new Core_Model_DbTable_DunnageInfoMaterial();
        $dunnage_material_info = $dunnage_material_db->getFullJoin($id);

        $dunnage_update_db = new Core_Model_DbTable_UpdateDunnageOperations();
        $dunnage_update_info = $dunnage_update_db->getUpdateDunnageOperation($id, 0, 1);
        
        if ( $dunnage_update_info->count() > 0 ) {
            $fields = $dunnage_update_db->getUpdateDunnageOperationCols($dunnage_update_info[0]);
        } else {
            $fields = $dunnage_update_db->getUpdateDunnageOperationCols();
        }
        $this->view->update_dunnage_operation_cols = $fields;        

        $dunnage_document_db = new Core_Model_DbTable_DunnageDocuments();
        $dunnage_document_info = $dunnage_document_db->getDunnageDocument($id);
        $this->view->operation = $dunnage_operation_info;
        $this->view->materials = $dunnage_material_info;
        $this->view->update = $dunnage_update_info;
        $this->view->documents = $dunnage_document_info;
        $this->view->dunnage  = 1;
        $this->view->dunnage_id = $id;
    }
    
    public function moreUpdateDunnageAction() {
        $this->_helper->layout()->disableLayout();
        $id = $this->_getParam("id");
        $offset = $this->_getParam("offset", 0);
        if( empty($id) ) {
            $this->_handlePageNotFound();
        }
        $dunnage_update_db = new Core_Model_DbTable_UpdateDunnageOperations();
        $dunnage_update_info = $dunnage_update_db->getUpdateDunnageOperation($id, $offset, 3);
        if ( $dunnage_update_info->count() > 0 ) {
            $fields = $dunnage_update_db->getUpdateDunnageOperationCols($dunnage_update_info[0]);
        } else {
            $fields = $dunnage_update_db->getUpdateDunnageOperationCols();
        }
        $this->view->update_dunnage_operation_cols = $fields;        
        $this->view->update = $dunnage_update_info;
    }

    public function detailCargo(){
        $id = $this->_getParam("id");
        if($id == -1){
            $this->_handlePageNotFound();
        }

        $cargo_operation_db = new Core_Model_DbTable_CargoOperations();
        $cargo_operation_info = $cargo_operation_db->getCargoOperation($id);

        $cargo_document_db = new Core_Model_DbTable_CargoDocuments();
        $cargo_document_pic = $cargo_document_db->getCargoPicture($id);
        $cargo_document_video = $cargo_document_db->getCargoVideo($id);

        $this->view->operation = $cargo_operation_info;
        $this->view->pics = $cargo_document_pic;
        $this->view->videos = $cargo_document_video;
        $this->view->cargo = 1;
    }

    public function cargoAction() {

    }

    public function dunnageAction() {
        
    }

    public function tallyAction() {
        
    }

    public function newAction() {
        $role = Core_Util::getRole();
        if(!$role){
            $this->_handlePageNotFound();
        }
        if(!($role == Core_Role::ROLE_ADMIN || $role == Core_Role::ROLE_INPUT)){
            $this->_handlePageNotFound();
        }
        $step = $this->_getParam("step", "new");
        switch ($step) {
            case "new":
                $this->handleNewStep();
                break;
            case 'generalinfo':
                $this->handleNewGeneralInfo();
                break;
            case 'dunnage':
                $this->handleNewDunnage();
                break;
            case "cargo":
                $this->handleNewCargo();
                
                break;
            case "tally":
                $this->handleNewTally();
                break;
            default:
                $view = "new";
                break;
        }
    }
    
    private function handleNewTally() {
        $ref_no = $this->_getParam("ref_no");
        if ( empty($ref_no) ) {
            $this->_handlePageNotFound();
        }
        if ( $this->getRequest()->isPost() ) {
            $tally_operation_data = array (
                'vessel_arrived_at_ps' => $this->_getTimestampParam("vessel_arrived_at_ps"),
                'vessel_arrived_at_buoy' => $this->_getTimestampParam("vessel_arrived_at_buoy"),
                'commenced_dunnaging' => $this->_getTimestampParam("commenced_dunnaging"),
                'completed_dunnaging' => $this->_getTimestampParam("completed_dunnaging"),
                'cargo_loaded_on_board' => $this->_getParam("cargo_loaded_on_board"),
                'number_of_bags' => $this->_getParam("number_of_bags"),
                'net_weight' => $this->_getParam("net_weight"),
                'gross_weight' => $this->_getParam("gross_weight"),
                'total_cargo_loaded_last_24h' => $this->_getParam("total_cargo_loaded_last_24h"),
                'total_cargo_loaded_upto_date' => $this->_getParam('total_cargo_loaded_upto_date'),
                'balance_to_load' => $this->_getParam('balance_to_load'),
                'ets' => $this->_getTimestampParam('ets'),
                'ats' => $this->_getTimestampParam('ats'),
                'created_time' => time()
            );
            
            $tally_operation_db = new Core_Model_DbTable_TallyOperations();
            $tally_operation_id = $tally_operation_db->insert($tally_operation_data);
            $transaction_db = new Core_Model_DbTable_Transactions();
            $transaction_db->updateTallyOperationId($ref_no, $tally_operation_id);
            
            $documents = $this->_getParam("documents");
            if ( !empty($documents) ) {
                $tally_document_db = new Core_Model_DbTable_TallyDocuments();
                foreach ($documents as $document)
                {
                    $document_data = array (
                        'tally_operation_id' => $tally_operation_id,
                        'file' => $document,
                        'created_time' => time()
                    ); 
                    $tally_document_db->insert($document_data);
                }
            }

            $this->_redirectNextStep();
        } else {
            $this->view->ref_no = $ref_no;
            $this->render("newtally");
        }
    }
    
    private function handleNewCargo() {
        $ref_no = $this->_getParam("ref_no");
        if ( empty($ref_no) ) {
            $this->_handlePageNotFound();
        }
        if ( $this->getRequest()->isPost() ) {
            $cargo_operation_data = array (
                'vessel_arrived_at_ps' => $this->_getTimestampParam("vessel_arrived_at_ps"),
                'vessel_arrived_at_buoy' => $this->_getTimestampParam("vessel_arrived_at_buoy"),
                'commenced_dunnaging' => $this->_getTimestampParam("commenced_dunnaging"),
                'completed_dunnaging' => $this->_getTimestampParam("completed_dunnaging"),
                'cargo_loaded_on_board' => $this->_getParam("cargo_loaded_on_board"),
                'number_of_bags' => $this->_getParam("number_of_bags"),
                'net_weight' => $this->_getParam("net_weight"),
                'gross_weight' => $this->_getParam("gross_weight"),
                'total_cargo_loaded_last_24h' => $this->_getParam("total_cargo_loaded_last_24h"),
                'total_cargo_loaded_upto_date' => $this->_getParam('total_cargo_loaded_upto_date'),
                'balance_to_load' => $this->_getParam('balance_to_load'),
                'ets' => $this->_getTimestampParam('ets'),
                'ats' => $this->_getTimestampParam('ats')
            );
            $cargo_operation_db = new Core_Model_DbTable_CargoOperations();
            $cargo_operation_id = $cargo_operation_db->insert($cargo_operation_data);
            
            $transaction_db = new Core_Model_DbTable_Transactions();
            $transaction_db->updateCargoOperationId($ref_no, $cargo_operation_id);
            
            $pictures = $this->_getParam("pictures");
            $cargo_document_db = new Core_Model_DbTable_CargoDocuments();
            if ( !empty($pictures) ) {
                foreach ($pictures as $picture)
                {
                    $document_data = array (
                        'type' => 'picture',
                        'file' => $picture,
                        'created_time' => time(),
                        'cargo_operation_id' => $cargo_operation_id
                    ); 
                    $cargo_document_db->insert($document_data);
                }
            }        
            
            $videos = $this->_getParam("videos");
            if ( !empty($videos) ) {
                foreach ($videos as $video) {
                    $cargo_video_data = array (
                        'type' => 'video',
                        'file' => $video,
                        'created_time' => time(),
                        'cargo_operation_id' => $cargo_operation_id
                    );
                    $cargo_document_db->insert($cargo_video_data);
                }
            }
            
            $this->_redirectNextStep();
        } else {
            $this->view->ref_no = $ref_no;
            $this->render("newcargo");
        }
        
    }

    private function handleNewStep() {
        if ($this->getRequest()->isPost()) {
            $dunnage = $this->_getParam("dunnage");
            $cargo = $this->_getParam("cargo");
            $tally = $this->_getParam("tally");
            $services = array();
            if ($dunnage) {
                $services[] = 'dunnage';
            }
            if ($tally) {
                $services[] = 'tally';
            }
            if ($cargo) {
                $services[] = 'cargo';
            }            
            $next_url = $this->view->serverUrl($this->view->baseUrl() . "/service/new/step/generalinfo/services/" . json_encode($services));
            $this->_redirect($next_url);
        }
    }

    private function _redirectNextStep() {
        $services_param = $this->_getParam("services");
        $step = $this->_getParam("step");
        if (!empty($services_param) && !empty($step)) {
            $steps = array(
                'new',
                'generalinfo'
            );
            $services = json_decode($services_param);
            $steps = array_merge($steps, $services);
            for ($i = 0; $i < sizeof($steps); $i++) {
                if ($step == $steps[$i]) {
                    break;
                }
            }
            if ($i < sizeof($steps) - 1) {
                $next_step = $steps[$i + 1];
                $next_url = $this->view->serverUrl($this->view->url(array(
                                    'controller' => 'service',
                                    'action' => 'new',
                                    'step' => $next_step,
                                    'services' => $services_param,
                                    'ref_no' => $this->_getParam("ref_no"))
                                )
                            );
                $this->_redirect($next_url);
                return true;
            } else {
                return false;
            }
        } else {
            $services = NULL;
        }
        return $services;
    }

    protected function handleNewGeneralInfo() {
        if ($this->getRequest()->isPost()) {
            $ref_no = $this->_getParam("ref_no");
            if ( empty($ref_no) ) {
                $this->_handlePageNotFound();
            }
            $upload_path = $this->getUploadDirectory($ref_no);
            $data = array(
                'customer_id' => $this->_getParam("customer_name"),
                'ship_name' => $this->_getParam("ship_name"),
                'port_id' => $this->_getParam("port_of_call"),
                'buoy_id' => $this->_getParam("buoy_name"),
                'cargo_quantity' => $this->_getParam("cargo_quantity"),
                'cargo_unit' => $this->_getParam("cargo_unit"),
                'eta' => $this->_getTimestampParam("eta"),
                'ata' => $this->_getTimestampParam("ata"),
                'ets' => $this->_getTimestampParam("ets"),
                'ats' => $this->_getTimestampParam("ats"),
                'ship_on_arrival' => $this->uploadFile("ship_on_arrival", $upload_path),
                'ship_on_departure' => $this->uploadFile("ship_on_departure", $upload_path),
                'created_time' => time()
            );

            $general_info_db = new Core_Model_DbTable_GeneralInformation();
            $general_info_id = $general_info_db->insert($data);

            $transaction_data = array(
                'ref_no' => $ref_no,
                'general_information_id' => $general_info_id,
                'created_time' => time(),
                'input_user' => $this->session->user->id,
            );
            $transaction_db = new Core_Model_DbTable_Transactions();
            $transaction_db->insert($transaction_data);

            $this->_redirectNextStep();
        } else {
            $port_db = new Core_Model_DbTable_Ports();
            $this->view->ports = $port_db->getAll();

            $user_db = new Core_Model_DbTable_Users();
            $this->view->customers = $user_db->getCustomers();

            $transaction_db = new Core_Model_DbTable_Transactions();
            $this->view->ref_no = $transaction_db->generateRefNo();

            $this->render("generalinfo");
        }
    }

    private function handleNewDunnage() {
        $ref_no = $this->_getParam("ref_no");
        if ( empty($ref_no) ) {
            $this->_handlePageNotFound();
        }
        if ($this->getRequest()->isPost()) {
            $dunnage_operation_db = new Core_Model_DbTable_DunnageOperations();
            $dunnage_operation_data = array(
                'vessel_arrived_at_ps' => $this->_getTimestampParam("vessel_arrived_at_ps"),
                'vessel_arrived_at_buoy' => $this->_getTimestampParam("vessel_arrived_at_buoy"),
                'commenced_dunnaging' => $this->_getTimestampParam("commenced_dunnaging"),
                'completed_dunnaging' => $this->_getTimestampParam("completed_dunnaging")
            );
            $dunnage_operation_id = $dunnage_operation_db->insert($dunnage_operation_data);

            $dunnage_material_ids = $this->_getParam("dunnage_material_id");
            $estimated_dunnage_usages = $this->_getParam("estimated_dunnage_usage");
            $final_dunnage_usages = $this->_getParam("final_dunnage_usage");
            $estimated_dunnage_costs = $this->_getParam("estimated_dunnage_cost");
            $final_dunnage_costs = $this->_getParam("final_dunnage_cost");

            $dunnage_info_material_db = new Core_Model_DbTable_DunnageInfoMaterial();
            $index = 0;
            foreach ($dunnage_material_ids as $dunnage_material_id) {
                $estimated_dunnage_usage = !empty($estimated_dunnage_usages[$index]) ? $estimated_dunnage_usages[$index] : NULL;
                $final_dunnage_usage = !empty($final_dunnage_usages[$index]) ? $final_dunnage_usages[$index] : NULL;
                $estimated_dunnage_cost = !empty($estimated_dunnage_costs[$index]) ? $estimated_dunnage_costs[$index] : NULL;
                $final_dunnage_cost = !empty($final_dunnage_costs[$index]) ? $final_dunnage_costs[$index] : NULL;
                $data = array (
                    'dunnage_operation_id' => $dunnage_operation_id,
                    'dunnage_material_id' => $dunnage_material_id,
                    'estimated_dunnage_usage' => $estimated_dunnage_usage,
                    'final_dunnage_usage' => $final_dunnage_usage,
                    'estimated_dunnage_cost' => $estimated_dunnage_cost,
                    'final_dunnage_cost' => $final_dunnage_cost,
                    'created_date' => time()
                );
                $dunnage_info_material_db->insert($data);
                $index++;
            }

            $transaction_db = new Core_Model_DbTable_Transactions();
            $transaction_db->updateDunnageOperationId($ref_no, $dunnage_operation_id);

            $upload_path = $this->getUploadDirectory($ref_no);

            $update_dunnage_operation_data = array (
                'date' => $this->_getTimestampParam("update_dunnage_date"),
                'laying_draft_paper' => $this->uploadFile("laying_draft_paper", $upload_path),
                'laying_plastic_sheets' => $this->uploadFile("laying_plastic_sheets", $upload_path),
                'sawdust_in_frame' => $this->uploadFile("sawdust_in_frame", $upload_path),
                'styrofoam_in_frame' => $this->uploadFile("styrofoam_in_frame", $upload_path),
                'kraft_paper_on_top' => $this->uploadFile("kraft_paper_on_top", $upload_path),
                'laying_bamboo_mats' => $this->uploadFile("laying_bamboo_mats", $upload_path),
                'laying_bamboo_sticks' => $this->uploadFile("laying_bamboo_sticks", $upload_path),
                'laying_ballets' => $this->uploadFile("laying_ballets", $upload_path),
                'dunnage_operation_id' => $dunnage_operation_id
            );

            $update_dunnage_operation_db = new Core_Model_DbTable_UpdateDunnageOperations();
            $update_dunnage_operation_db->insert($update_dunnage_operation_data);

            $documents = $this->_getParam("documents");
            if ( !empty($documents) ) {
                $dunnage_document_db = new Core_Model_DbTable_DunnageDocuments();
                foreach ($documents as $document)
                {
                    $document_data = array (
                        'dunnage_id' => $dunnage_operation_id,
                        'file' => $document,
                        'created_time' => time()
                    ); 
                    $dunnage_document_db->insert($document_data);
                }
            }

            $this->_redirectNextStep();
        } else {
            $dunnage_db = new Core_Model_DbTable_DunnageMaterials();
            $this->view->dunnage_services = $dunnage_db->getAll();
            $this->view->ref_no = $this->_getParam("ref_no");
            $this->render("newdunnage");
        }
    }

    public function getbuoysAction() {
        $this->setAjaxCall();

        $buoy_db = new Core_Model_DbTable_Buoys();
        $port_id = $this->_getParam("pid");
        if (!empty($port_id)) {
            $buoys = $buoy_db->getBuoyByPort($port_id);
            echo json_encode($buoys->toArray());
        } else {
            echo json_encode(array());
        }
    }

    public function pluploadAction() {

        $this->setAjaxCall();

        $id = $this->_getParam("id");
        // Settings
        $targetDir = $this->getUploadDirectory($id);
        //$targetDir = 'uploads';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        // usleep(5000);
        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

        // Make sure the fileName is unique but only if chunking is disabled
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);

            $count = 1;
            while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                $count++;

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Create target dir
        if (!file_exists($targetDir))
            @mkdir($targetDir);

        // Remove old temp files	
        if ($cleanupTargetDir) {
            if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
                while (($file = readdir($dir)) !== false) {
                    $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                    // Remove temp file if it is older than the max age and is not the current file
                    if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
                        @unlink($tmpfilePath);
                    }
                }
                closedir($dir);
            } else {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
        }

        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
            $contentType = $_SERVER["CONTENT_TYPE"];

        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = @fopen($_FILES['file']['tmp_name'], "rb");

                    if ($in) {
                        while ($buff = fread($in, 4096))
                            fwrite($out, $buff);
                    }
                    else
                        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                    @fclose($in);
                    @fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                }
                else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            else
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        } else {
            // Open temp file
            $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = @fopen("php://input", "rb");

                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                }
                else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

                @fclose($in);
                @fclose($out);
            }
            else
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off 
            rename("{$filePath}.part", $filePath);
        }

        $relative_file_path = str_replace(UPLOAD_PATH, "", $filePath);
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "path": "' . $relative_file_path . '", "file_name": "' . $fileName . '"}');
    }
    
    private function getUploadDirectory($id) {
        $year = date('Y');
        $month = date('m');
        $day = date('d');
        $upload_path = UPLOAD_PATH . $year;
        if ( !file_exists($upload_path) ) {
            mkdir($upload_path);
        }
        $upload_path .= DIRECTORY_SEPARATOR . $month;
        if ( !file_exists($upload_path) ) {
            mkdir($upload_path);
        }
        
        $upload_path .= DIRECTORY_SEPARATOR . $day;
        if ( !file_exists($upload_path) ) {
            mkdir($upload_path);
        }
        
        $upload_path .= DIRECTORY_SEPARATOR . $id;
        if ( !file_exists($upload_path) ) {
            mkdir($upload_path);
        }
        
        return $upload_path;
    }
    
    public function deleteUploadFileAction() {
        $this->setAjaxCall();
        
        $file_name = $this->_getParam("file_name");
        if ( empty($file_name) ) {
            return;
        }
        $id = $this->_getParam("id");
        if ( $id ) {
            $service_type = $this->_getParam("service_type");
            if ( $service_type ) {
                $class_name = "Core_Model_DbTable_" . $service_type . "Documents";
                $cargo_documents_db = new $class_name();
                $cargo_documents_db->delete("id = $id");
            }
        }
        $full_file_name = UPLOAD_PATH . $file_name;
        unlink($full_file_name);
    }
    
    protected function _getParam($paramName, $default = null) {
        $value = parent::_getParam($paramName, $default);
        if ( empty($value) && $default === NULL ) {
            return NULL;
        } else {
            return $value;
        }
    }

    public function updateAction(){
        if(!Core_Util::hasAccess($this->_getParam("tid"))){
            $this->_handlePageNotFound();
        }
        $step = $this->_getParam("step", "update");
        switch ($step) {
            case "update":
                $this->handleUpdateStep();
                break;
            case 'generalinfo':
                $this->handleUpdateGeneralInfo();
                break;
            case 'dunnage':
                $this->handleUpdateDunnage();
                break;
            case "cargo":
                $this->handleUpdateCargo();
                break;
            case "tally":
                $this->handleUpdateTally();
                break;
            default:
                $view = "new";
                break;
        }
    }

    private function handleUpdateStep() {
        if ($this->getRequest()->isPost()) {
            $dunnage = $this->_getParam("dunnage");
            $cargo = $this->_getParam("cargo");
            $tally = $this->_getParam("tally");
            $services = array();
            if ($dunnage) {
                $services[] = 'dunnage';
            }
            if ($tally) {
                $services[] = 'tally';
            }
            if ($cargo) {
                $services[] = 'cargo';
            }
            $next_url = $this->view->serverUrl($this->view->baseUrl() . "/service/update/step/generalinfo/services/" . json_encode($services));
            $this->_redirect($next_url);
        }
    }

    protected function handleUpdateGeneralInfo() {
        if ($this->getRequest()->isPost()) {
            $id = $this->_getParam("general_id");
            $ref_no = $this->_getParam("ref_no");
            if ( empty($ref_no) ) {
                $this->_handlePageNotFound();
            }
            $upload_path = $this->getUploadDirectory($ref_no);
            $ship_on_arrival = $this->uploadFile("ship_on_arrival", $upload_path);
            $ship_on_departure = $this->uploadFile("ship_on_departure", $upload_path);
            $data = array(
                'customer_id' => $this->_getParam("customer_name"),
                'ship_name' => $this->_getParam("ship_name"),
                'port_id' => $this->_getParam("port_of_call"),
                'buoy_id' => $this->_getParam("buoy_name"),
                'cargo_quantity' => $this->_getParam("cargo_quantity"),
                'cargo_unit' => $this->_getParam("cargo_unit"),
                'eta' => $this->_getTimestampParam("eta"),
                'ata' => $this->_getTimestampParam("ata"),
                'ets' => $this->_getTimestampParam("ets"),
                'ats' => $this->_getTimestampParam("ats")
            );
            
            if ( !empty($ship_on_arrival) ) {
                $data['ship_on_arrival'] = $this->uploadFile("ship_on_arrival", $upload_path);
            }
            if ( !empty($ship_on_departure) ) {
                $data['ship_on_departure'] = $this->uploadFile("ship_on_departure", $upload_path);
            }
            $general_info_db = new Core_Model_DbTable_GeneralInformation();
            $general_info_db->update($data,"id = {$id}");
            $next_url = $this->view->serverUrl($this->view->baseUrl() . "/tracking");
            $this->redirect($next_url);
        } else {
            $user_db = new Core_Model_DbTable_Users();
            $this->view->customers = $user_db->getCustomers();

            $transaction_db = new Core_Model_DbTable_Transactions();
            $id = $this->_getParam("id");
            if(empty($id) || is_null($id)) {
                $this->_handlePageNotFound();
            }
            
            $transaction = $transaction_db->getTransaction($id);
            $this->view->transaction = $transaction;
            $this->view->ref_no = $this->view->transaction["ref_no"];

            $general_info_db = new Core_Model_DbTable_GeneralInformation();
            $genereral_info = $general_info_db->get($transaction['general_information_id']);
            $this->view->general_information = $genereral_info;
            
            $port_db = new Core_Model_DbTable_Ports();
            $this->view->ports = $port_db->getAll();
            
            $buoy_db = new Core_Model_DbTable_Buoys();
            $this->view->buoys = $buoy_db->getBuoyByPort($genereral_info['port_id']);
            
            $this->render("generalinfo");
        }
    }

    private function handleUpdateDunnage() {
        if ($this->getRequest()->isPost()) {
            $ref_no = $this->_getParam("ref_no");
            if ( empty($ref_no) ) {
                $this->_handlePageNotFound();
            }
            $dunnage_operation_db = new Core_Model_DbTable_DunnageOperations();
            $id = $this->_getParam("dunnage_id");
            $dunnage_operation_data = array (
                'vessel_arrived_at_ps' => $this->_getTimestampParam("vessel_arrived_at_ps"),
                'vessel_arrived_at_buoy' => $this->_getTimestampParam("vessel_arrived_at_buoy"),
                'commenced_dunnaging' => $this->_getTimestampParam("commenced_dunnaging"),
                'completed_dunnaging' => $this->_getTimestampParam("completed_dunnaging")
            );

            $dunnage_operation_db->update($dunnage_operation_data, "id = {$id}");

            $dunnage_material_ids = $this->_getParam("dunnage_material_id");
            $estimated_dunnage_usages = $this->_getParam("estimated_dunnage_usage");
            $final_dunnage_usages = $this->_getParam("final_dunnage_usage");
            $estimated_dunnage_costs = $this->_getParam("estimated_dunnage_cost");
            $final_dunnage_costs = $this->_getParam("final_dunnage_cost");

            $dunnage_info_material_db = new Core_Model_DbTable_DunnageInfoMaterial();
            $index = 0;
            foreach ($dunnage_material_ids as $dunnage_material_id) {
                $estimated_dunnage_usage = !empty($estimated_dunnage_usages[$index]) ? $estimated_dunnage_usages[$index] : NULL;
                $final_dunnage_usage = !empty($final_dunnage_usages[$index]) ? $final_dunnage_usages[$index] : NULL;
                $estimated_dunnage_cost = !empty($estimated_dunnage_costs[$index]) ? $estimated_dunnage_costs[$index] : NULL;
                $final_dunnage_cost = !empty($final_dunnage_costs[$index]) ? $final_dunnage_costs[$index] : NULL;
                $data = array(
                    'estimated_dunnage_usage' => $estimated_dunnage_usage,
                    'final_dunnage_usage' => $final_dunnage_usage,
                    'estimated_dunnage_cost' => $estimated_dunnage_cost,
                    'final_dunnage_cost' => $final_dunnage_cost,
                );
                $dunnage_info_material_db->update($data, "dunnage_operation_id = {$id} and dunnage_material_id = {$dunnage_material_id}");
                $index++;
            }

            $transaction_db = new Core_Model_DbTable_Transactions();
            $transaction_db->updateDunnageOperationId($ref_no, $id);

            $upload_path = $this->getUploadDirectory($ref_no);

            $update_dunnage_operation_data = array (
                'date' => $this->_getTimestampParam("update_dunnage_date"),
                'laying_draft_paper' => $this->uploadFile("laying_draft_paper", $upload_path),
                'laying_plastic_sheets' => $this->uploadFile("laying_plastic_sheets", $upload_path),
                'sawdust_in_frame' => $this->uploadFile("sawdust_in_frame", $upload_path),
                'styrofoam_in_frame' => $this->uploadFile("styrofoam_in_frame", $upload_path),
                'kraft_paper_on_top' => $this->uploadFile("kraft_paper_on_top", $upload_path),
                'laying_bamboo_mats' => $this->uploadFile("laying_bamboo_mats", $upload_path),
                'laying_bamboo_sticks' => $this->uploadFile("laying_bamboo_sticks", $upload_path),
                'laying_ballets' => $this->uploadFile("laying_ballets", $upload_path),
                'dunnage_operation_id' => $id
            );

            $update_dunnage_operation_db = new Core_Model_DbTable_UpdateDunnageOperations();
            if ( !$update_dunnage_operation_db->isEmpty($update_dunnage_operation_data) ) {
                $update_dunnage_operation_db->insert($update_dunnage_operation_data);
            }

            $documents = $this->_getParam("documents");
            if ( !empty($documents) ) {
                $dunnage_document_db = new Core_Model_DbTable_DunnageDocuments();
                foreach ($documents as $document)
                {
                    $document_data = array (
                        'dunnage_id' => $id,
                        'file' => $document,
                        'created_time' => time()
                    );
                    $dunnage_document_db->insert($document_data);
                }
            }
            $next_url = $this->view->serverUrl($this->view->baseUrl() . "/tracking");
            $this->redirect($next_url);

        } else {
            $id = $this->_getParam("id");
            if(is_null($id) || empty($id)){
                $this->_handlePageNotFound();
            }
            $dunnage_db = new Core_Model_DbTable_DunnageMaterials();
            $this->view->dunnage_services = $dunnage_db->getAll();
            $this->view->ref_no = $this->_getParam("ref_no");
            $this->view->id = $id;
            $dunnage_material_db = new Core_Model_DbTable_DunnageInfoMaterial();
            $this->view->dunnage_material = $dunnage_material_db->getDunnageMaterial($id);

            $dunnage_operation_db = new Core_Model_DbTable_DunnageOperations();
            $this->view->dunnage_operation = $dunnage_operation_db->getDunnageOperation($id);

            $update_dunnage_operation_db = new Core_Model_DbTable_UpdateDunnageOperations();
            $update_dunnage_operations = $update_dunnage_operation_db->getUpdateDunnageOperation($id);
            $this->view->update_dunnage_operations = $update_dunnage_operations;
            if ( $update_dunnage_operations->count() > 0 ) {
                $fields = $update_dunnage_operation_db->getUpdateDunnageOperationCols($update_dunnage_operations[0]);
            } else {
                $fields = $update_dunnage_operation_db->getUpdateDunnageOperationCols();
            }
            
            $this->view->update_dunnage_operation_cols = $fields;

            $dunnage_document_db = new Core_Model_DbTable_DunnageDocuments();
            $this->view->dunnage_document = $dunnage_document_db->getDunnageDocument($id);
            $this->render("newdunnage");
        }
    }

    private function handleUpdateCargo() {
        if ( $this->getRequest()->isPost() ) {
            $ref_no = $this->_getParam("ref_no");
            $id = $this->_getParam("cargo_id");
            if(empty($ref_no)) {
                $this->_handlePageNotFound();
            }
            $cargo_operation_data = array (
                'vessel_arrived_at_ps' => $this->_getTimestampParam("vessel_arrived_at_ps"),
                'vessel_arrived_at_buoy' => $this->_getTimestampParam("vessel_arrived_at_buoy"),
                'commenced_dunnaging' => $this->_getTimestampParam("commenced_dunnaging"),
                'completed_dunnaging' => $this->_getTimestampParam("completed_dunnaging"),
                'cargo_loaded_on_board' => $this->_getParam("cargo_loaded_on_board"),
                'number_of_bags' => $this->_getParam("number_of_bags"),
                'net_weight' => $this->_getParam("net_weight"),
                'gross_weight' => $this->_getParam("gross_weight"),
                'total_cargo_loaded_last_24h' => $this->_getParam("total_cargo_loaded_last_24h"),
                'total_cargo_loaded_upto_date' => $this->_getParam('total_cargo_loaded_upto_date'),
                'balance_to_load' => $this->_getParam('balance_to_load'),
                'ets' => $this->_getTimestampParam('ets'),
                'ats' => $this->_getTimestampParam('ats')
            );
            $cargo_operation_db = new Core_Model_DbTable_CargoOperations();
            $cargo_operation_db->update($cargo_operation_data, "id = $id");

            $pictures = $this->_getParam("pictures");
            $cargo_document_db = new Core_Model_DbTable_CargoDocuments();
            if ( !empty($pictures) ) {
                foreach ($pictures as $picture)
                {
                    $document_data = array (
                        'type' => 'picture',
                        'file' => $picture,
                        'created_time' => time(),
                        'cargo_operation_id' => $id
                    );
                    $cargo_document_db->insert($document_data);
                }
            }

            $videos = $this->_getParam("videos");
            if ( !empty($videos) ) {
                foreach ($videos as $video) {
                    $cargo_video_data = array (
                        'type' => 'video',
                        'file' => $video,
                        'created_time' => time(),
                        'cargo_operation_id' => $id
                    );
                    $cargo_document_db->insert($cargo_video_data);
                }
            }

            $next_url = $this->view->serverUrl($this->view->baseUrl() . "/tracking");
            $this->redirect($next_url);
        } else {
            $ref_no = $this->_getParam("ref_no");
            $id = $this->_getParam("id");
            if(!$ref_no || !$id) {
                $this->_handlePageNotFound();
            }
            $this->view->id = $id;
            $this->view->ref_no = $ref_no;
            $cargo_operation_db = new Core_Model_DbTable_CargoOperations();
            $this->view->cargo_operation = $cargo_operation_db->getCargoOperation($id);

            $cargo_document = new Core_Model_DbTable_CargoDocuments();
            $this->view->pictures = $cargo_document->getCargoPicture($id);
            $this->view->videos = $cargo_document->getCargoVideo($id);
            $this->render("newcargo");
        }
    }
    
    public function deleteUpdateDunnageOperationAction() {
        $this->setAjaxCall();
        
        if ( $this->getRequest()->isPost() ) {
            $update_dunnage_id = $this->_getParam("id");
            if ( !empty($update_dunnage_id) ) {
                $update_dunnage_operation_db = new Core_Model_DbTable_UpdateDunnageOperations();
                echo $update_dunnage_operation_db->deleteById($update_dunnage_id);
            }
        } else {
            $this->_handlePageNotFound();
        }
    }
}

?>
